﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Configuration;
using System.Security.Cryptography;

namespace Event_SG_EWDT
{
    public class Utility
    {
        #region Upload

        //public static bool IsFileExists(string fileToCompare)
        //{
        //    return false;
        //}

        //public static int NormaliseFileName(string fileNameToNormalise)
        //{
        //    return fileNameToNormalise.GetHashCode();
        //}

        public static string[] GetFilesWithExtension(string path)
        {
            return System.IO.Directory.GetFiles(path);
        }

        public static string GetFilenameWithExtensionForThumbnail(string path)
        {
            string[] s = System.IO.Directory.GetFiles(path);

            foreach (string _s in s)
            {
                if (_s.IndexOf("thumbnail") != -1)
                {
                    return _s.Substring(_s.IndexOf("thumbnail"));
                }
            }

            return "";
        }

        public static string GetFilenameWithExtensionForPoster(string path)
        {
            string[] s = System.IO.Directory.GetFiles(path);

            foreach (string _s in s)
            {
                if (_s.IndexOf("poster") != -1)
                {
                    return _s.Substring(_s.IndexOf("poster"));
                }
            }

            return "";
        }

        public static string GetGroupThumbnailPath(HttpServerUtility server, string groupId)
        {
            string path = String.Format("{0}{1}{2}", GetServerDiskPath(server), @"resources\groups\", groupId);

            if (IsFolderExists(path))
            {
                //************************************************ NEED TO UPDATE

                return String.Format("~/resources/groups/{0}/" + GetFilenameWithExtensionForThumbnail(path), groupId);
            }
            else
            {
                //************************************************ NEED TO UPDATE
                return "~/images/cloud.png";
            }
        }

        public static string GetGroupPosterPath(HttpServerUtility server, string groupId)
        {
            //string path = String.Format("{0}{1}", GetServerDiskPath(server), eventId);
            string path = String.Format("{0}{1}{2}", GetServerDiskPath(server), @"resources\groups\", groupId);


            if (IsFolderExists(path))
            {
                //************************************************ NEED TO UPDATE
                //return String.Format("~/{0}/poster.jpg", eventId);

                //return String.Format("~/resources/events/{0}/poster.jpg", eventId);

                return String.Format("~/resources/groups/{0}/" + GetFilenameWithExtensionForPoster(path), groupId);

            }
            else
            {
                //************************************************ NEED TO UPDATE
                return "~/images/cloud.png";
            }
        }

        public static string GetEventThumbnailPath(HttpServerUtility server, string eventId)
        {
            string path = String.Format("{0}{1}{2}", GetServerDiskPath(server), @"resources\events\", eventId);

            if (IsFolderExists(path))
            {
                //************************************************ NEED TO UPDATE
               // return String.Format("~/{0}/thumbnail.jpg", eventId);

                //return String.Format("~/resources/events/{0}/thumbnail.jpg", eventId);

                return String.Format("~/resources/events/{0}/" + GetFilenameWithExtensionForThumbnail(path), eventId);


            }
            else
            {
                //************************************************ NEED TO UPDATE
                return "~/images/feed.png";
            }
        }

        public static string GetEventPosterPath(HttpServerUtility server, string eventId)
        {
            //string path = String.Format("{0}{1}", GetServerDiskPath(server), eventId);
            string path = String.Format("{0}{1}{2}", GetServerDiskPath(server), @"resources\events\", eventId);


            if (IsFolderExists(path))
            {
                //************************************************ NEED TO UPDATE
                //return String.Format("~/{0}/poster.jpg", eventId);

                //return String.Format("~/resources/events/{0}/poster.jpg", eventId);

                return String.Format("~/resources/events/{0}/" + GetFilenameWithExtensionForPoster(path), eventId);

            }
            else
            {
                //************************************************ NEED TO UPDATE
                return "~/images/feed.png";
            }
        }

        public static bool UploadGroupPoster(HttpServerUtility server, FileUpload fileUploader, string groupId)
        {
            try
            {
                int i = fileUploader.FileName.LastIndexOf(".");

                string fileExtension = (i != -1) ? fileUploader.FileName.Substring(i) : "";


                string savePath = String.Format(@"{0}\{1}", GetServerDiskPath(server) + @"resources\groups", groupId); //Concat a path which points to the user folder

                if (!IsFolderExists(savePath)) //If user has no folder
                {
                    CreateFolder(savePath); //Creates one for the user
                }

                fileUploader.SaveAs(String.Format(@"{0}\{1}{2}", savePath, "poster", fileExtension));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static bool UploadGroupThumbnail(HttpServerUtility server, FileUpload fileUploader, string groupId)
        {
            try
            {
                int i = fileUploader.FileName.LastIndexOf(".");

                string fileExtension = (i != -1) ? fileUploader.FileName.Substring(i) : "";


                string savePath = String.Format(@"{0}\{1}", GetServerDiskPath(server) + @"resources\groups", groupId); //Concat a path which points to the user folder

                if (!IsFolderExists(savePath)) //If user has no folder
                {
                    CreateFolder(savePath); //Creates one for the user
                }

                fileUploader.SaveAs(String.Format(@"{0}\{1}{2}", savePath, "thumbnail", fileExtension));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static bool UploadEventPoster(HttpServerUtility server, FileUpload fileUploader, string eventId)
        {
            try
            {
                int i = fileUploader.FileName.LastIndexOf(".");

                string fileExtension = (i != -1) ? fileUploader.FileName.Substring(i) : "";


                string savePath = String.Format(@"{0}\{1}", GetServerDiskPath(server) + @"resources\events", eventId); //Concat a path which points to the user folder

                if (!IsFolderExists(savePath)) //If user has no folder
                {
                    CreateFolder(savePath); //Creates one for the user
                }

                fileUploader.SaveAs(String.Format(@"{0}\{1}{2}", savePath, "poster", fileExtension));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static bool UploadEventThumbnail(HttpServerUtility server, FileUpload fileUploader, string eventId)
        {
            try
            {
                int i = fileUploader.FileName.LastIndexOf(".");

                string fileExtension = (i != -1) ? fileUploader.FileName.Substring(i) : "";


                string savePath = String.Format(@"{0}\{1}", GetServerDiskPath(server) + @"resources\events", eventId); //Concat a path which points to the user folder

                if (!IsFolderExists(savePath)) //If user has no folder
                {
                    CreateFolder(savePath); //Creates one for the user
                }

                fileUploader.SaveAs(String.Format(@"{0}\{1}{2}", savePath, "thumbnail", fileExtension));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static bool UploadFile(HttpServerUtility server, FileUpload fileUploader, string folderId)
        {
            try
            {

                //string[] s = fileUploader.FileName.Split(new char[] {'.'});
                //string fileExtension = (s.Length == 2) ? "." + s[1] : "";

                int i = fileUploader.FileName.LastIndexOf(".");

                string fileExtension = (i != -1) ? fileUploader.FileName.Substring(i) : "";


                string savePath = String.Format(@"{0}\{1}", GetServerDiskPath(server), folderId); //Concat a path which points to the user folder

                if (!IsFolderExists(savePath)) //If user has no folder
                {
                    CreateFolder(savePath); //Creates one for the user
                }

                fileUploader.SaveAs(String.Format(@"{0}\{1}{2}", savePath, GenerateNewFileName(savePath), fileExtension));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static string GenerateNewFileName(string path)
        {
            //May need to deprecate if working with zero bases filename
            return GetCountOfFilesInDir(path).ToString().GetHashCode().ToString();
        }

        public static int GetCountOfFilesInDir(string path)
        {
            return System.IO.Directory.GetFiles(path).Length;
        }

        public static bool IsFolderExists(string folderToCompare)
        {
            return System.IO.Directory.Exists(folderToCompare);
        }

        public static void CreateFolder(string absPathToNewFolder)
        {
            System.IO.Directory.CreateDirectory(absPathToNewFolder);
        }

        public static string GetServerDiskPath(HttpServerUtility server)
        {
            return server.MapPath("/");
        }

        #endregion

        #region Email

        #region pregenerated email msgs
        //{0} www.eventsg.com/registration.aspx?postbackurl=....
        //{1} www.eventsg.com/registration.aspx?group=....

        static string emailInviteToGroupMsg = @"Welcome Guest,

One of your friends has invited you to join their group in our website Event@SG.

We would like to invite you to our website to register if you are not yet a member.
The registration link is below:
{0} 
Or join the group directly if you are already a member. The sign in link is below:
{1} 
We look forward to serving you in the future.

Thanks,
Event@SG team";

        static string emailInviteToEventMsg = @"Welcome Guest,

One of your friends has invited you to join their event in our website Event@SG.

We would like to invite you to our website to register if you are not yet a member.
The registration link is below:
{0} 
Or join the group directly if you are already a member. The sign in link is below:
{1} 
We look forward to serving you in the future.

Thanks,
Event@SG team";
        #endregion

        public static void EmailJoinGroupMessage(HttpRequest request, string groupName, string groupId, string toEmail)
        {
            //ADDED TRIM
            toEmail = toEmail.Trim();

            string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);
            string registerUrl = serverUrl + "/registration.aspx?groupid=" + groupId;
            string loginUrl = serverUrl + "/registration.aspx?groupid=" + groupId;

            string emailSubject = String.Format("[Event@SG] Your friend has invited you to join group [{0}]", groupName);
            string emailBody = String.Format(emailInviteToGroupMsg, registerUrl, loginUrl);

            
            Email(toEmail, emailSubject, emailBody);
        }

        public static void EmailJoinEventMessage(HttpRequest request, string eventName, string eventId, string toEmail)
        {
            //ADDED TRIM
            toEmail = toEmail.Trim();

            string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);
            string registerUrl = serverUrl + "/registration.aspx?eventid=" + eventId;
            string loginUrl = serverUrl + "/registration.aspx?eventid=" + eventId;

            string emailSubject = String.Format("[Event@SG] Your friend has invited you to join event [{0}]", eventName);
            string emailBody = String.Format(emailInviteToGroupMsg, registerUrl, loginUrl);


            Email(toEmail, emailSubject, emailBody);
        }

        public static void EmailFeedBackToEventSG(string nameOfUser, string emailOfUser, string emailSubject, string emailBody)
        {
            string userEmail = "Sent from " + emailOfUser + "\t by " + nameOfUser + "\n";
            

            emailBody = userEmail + emailBody;

            Utility.Email(ConfigurationManager.AppSettings["mailuser"], emailSubject, emailBody);
        }

        //new need test
        public static bool EmailNewPasswordToUser(HttpRequest request, string userMail)
        {
            //do sql to see if user exists
            
            //store in var memberid;

            string memberId = MemberControls.RetrieveMemberByAccount(userMail).MembershipNo;

            if (memberId != "")
            {

                string newPassword = GenerateNewPassword();

                string hashedNewPassword = GenerateHashFromPassword(newPassword);

                //SQL Statement to modify user password; passing in hashedNewPassword as var

                MemberControls.UpdatePassword(memberId, hashedNewPassword);

                EmailPasswordChangeToUser(request, userMail, newPassword);

                return true;
            }

            return false;
        }

        public static void EmailPasswordChangeToUser(HttpRequest request,string userMail, string newPassword)
        {
            string url = GetServerUrl(request) + "/registration.aspx";

            string emailSubject = "[Event@SG] Your password has been reset";
            string emailBody = "Hello,\nAs per your request we have generated a new password for your account: \n\n" + newPassword + "\n\n\nHere's the link to test out your new password: " + url;

            Utility.Email(userMail, emailSubject, emailBody);
        }
        
        public static void Email(string toEmail, string emailSubject, string emailBody)
        {
            string from = ConfigurationManager.AppSettings["mailuser"];

            MailMessage mailMessage = new MailMessage(new MailAddress(from),
                                        new MailAddress(toEmail));

            mailMessage.Subject = emailSubject;
            mailMessage.Body = emailBody;
            mailMessage.IsBodyHtml = false;

            System.Net.NetworkCredential networkCredentials = new
            System.Net.NetworkCredential(from, ConfigurationManager.AppSettings["mailpassword"]);

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredentials;
            smtpClient.Host = ConfigurationManager.AppSettings["smtpserver"];
            smtpClient.Port = 587;
            smtpClient.Send(mailMessage);
        }


        #endregion

        private static Random r = new Random();

        public static string GenerateNewPassword()
        {
           
            string sample = "ABCDEFGHIJKLMNOPQRSTUVQXYZabdefghijklmnopqrstuvwxyz1234567890";
            string newpassword = "";                     

            for (int i = 0; i < 6; i++)
            {
                newpassword += sample[r.Next(0, sample.Length)];
            }

            return newpassword;
        }

        public static string GenerateHashFromPassword(string password)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] bytes = encoding.GetBytes(password);

            var md5 = new MD5CryptoServiceProvider();
            var md5data = md5.ComputeHash(bytes);

            var hashedPassword = System.Text.Encoding.ASCII.GetString(md5data);

            return hashedPassword;
        }

        

        #region Image
        public static void UploadEventPoster(FileUpload fu, string eventid)
        {
                //getting length of uploaded file
                int length = fu.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                byte[] imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = fu.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);

                string imageid = DBMANAGER.UploadImage(imgbyte);
                DBMANAGER.SetEventImagePoster(eventid, imageid);

        }

        public static void UploadEventThumbnail(FileUpload fu, string eventid)
        {
                //getting length of uploaded file
                int length = fu.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                byte[] imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = fu.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);

                string imageid = DBMANAGER.UploadImage(imgbyte);
                DBMANAGER.SetEventImageThumbnail(eventid, imageid);

        }
        public static void UploadGroupLogo(FileUpload fu, string groupid)
        {
                //getting length of uploaded file
                int length = fu.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                byte[] imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = fu.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);

                string imageid = DBMANAGER.UploadImage(imgbyte);
                DBMANAGER.SetGroupImageLogo(groupid, imageid);
            
        }

        public static void UploadGroupThumbnail(FileUpload fu, string groupid)
        {
            
                //getting length of uploaded file
                int length = fu.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                byte[] imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = fu.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);

                string imageid = DBMANAGER.UploadImage(imgbyte);
                DBMANAGER.SetGroupImageThumbnail(groupid, imageid);

        }
         
        public static void UploadDefaultPoster(string id)
        {
            DBMANAGER.SetEventImagePoster(id, "2");
        }
        public static void UploadDefaultLogo(string id)
        {
            DBMANAGER.SetGroupImageLogo(id, "1");
        }
        public static void UploadDefaultEventThumbnail(string id)
        {
            DBMANAGER.SetEventImageThumbnail(id, "1");
        }

        public static void UploadDefaultGroupThumbnail(string id)
        {
            DBMANAGER.SetGroupImageThumbnail(id, "1");
        }
        #endregion



        #region Notificaitons
            static string inviteToEventMsg = "Hi, You have been invited to an event,  {0} by {1}.\nHere's the event link: {2}";
            static string inviteToGroupMsg = "Hi, You have been invited to a group,  {0} by {1}.\nHere's the group link: {2}";

            public static void SendNotificationForEventInvite(HttpRequest request, string eventId, int sender, int receiver)
            {
                string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);

                string eventName = EventControl.RetrieveEvent(eventId).EventTitle;
                string senderName = MemberControls.RetrieveMember(sender.ToString()).Name;
                string Url = serverUrl + "/ViewEvent.aspx?eventid=" + eventId;

                string msg = String.Format(inviteToEventMsg, eventName, senderName, Url);
                
                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }

            public static void SendNotificationForGroupInvite(HttpRequest request, string groupId, int sender, int receiver)
            {
                string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);

                string groupName = GroupControl.RetrieveGroup(groupId).GroupName;
                string senderName = MemberControls.RetrieveMember(sender.ToString()).Name;
                string Url = serverUrl + "/ViewGroup.aspx?groupid=" + groupId;

                string msg = String.Format(inviteToGroupMsg, groupName, senderName, Url);

                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }

            static string interestToJoinEventMsg = "Hi, {0}, {1}, wishes to join your event, {2}.";
            static string interestToJoinGroupMsg = "Hi, {0}, {1}, wishes to join your group, {2}.";

            public static void SendJoinInterestToEventAdmin(int sender, int receiver, string eventid)
            {
                Event e = EventControl.RetrieveEvent(eventid);

                Member s = MemberControls.RetrieveMember(sender.ToString());
                string msg = String.Format(interestToJoinEventMsg, s.Name, s.Email, e.EventTitle);

                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }

            public static void SendJoinInterestToGroupAdmin(int sender, int receiver, string groupid)
            {
                Group g = GroupControl.RetrieveGroup(groupid);

                Member s = MemberControls.RetrieveMember(sender.ToString());
                string msg = String.Format(interestToJoinGroupMsg, s.Name, s.Email, g.GroupName);

                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }

            static string updatedEventMsg = "Hi, The event administrator for event - {0} has updated the event information.\nHere's the link {1}.";
            static string updatedGroupMsg = "Hi, The group administrator for group - {0} has updated the group information.\nHere's the link {1}.";

            public static void SendUpdateNotificationToEventMembers(HttpRequest request, int eventid)
            {
                string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);
                string Url = serverUrl + "/ViewEvent.aspx?eventid=" + eventid;

                List<Member> mList = NotificationControl.MemberFromEvent(eventid.ToString());
                List<Member> aList = NotificationControl.AdminFromEvent(eventid.ToString());

                Event e = EventControl.RetrieveEvent(eventid.ToString());

                string msg = String.Format(updatedEventMsg, e.EventTitle, Url);

                foreach (Member m in mList)
                {
                    foreach (Member a in aList)
                    {
                        NotificationControl.CreateNotification(Convert.ToInt32(a.MembershipNo), Convert.ToInt32(m.MembershipNo), msg, DateTime.Now);
                    }
                }
            }

            public static void SendUpdateNotificationToGroupMembers(HttpRequest request, int groupid)
            {
                string serverUrl = request.Url.GetLeftPart(UriPartial.Authority);
                string Url = serverUrl + "/ViewGroup.aspx?groupid=" + groupid;

                List<Member> mList = NotificationControl.MemberFromEvent(groupid.ToString());
                List<Member> aList = NotificationControl.AdminFromEvent(groupid.ToString());

                Group g = GroupControl.RetrieveGroup(groupid.ToString());

                string msg = String.Format(updatedEventMsg, g.GroupName, Url);

                foreach (Member m in mList)
                {
                    foreach (Member a in aList)
                    {
                        NotificationControl.CreateNotification(Convert.ToInt32(a.MembershipNo), Convert.ToInt32(m.MembershipNo), msg, DateTime.Now);
                    }
                }
            }

            static string acceptedEventMsg = "Hi, You have been accepted by {0}, to join event, {1}.";
            static string acceptedGroupMsg = "Hi, You have been accepted by {0}, to join group, {1}.";

            public static void SendAcceptedToEvent(int sender, int receiver, string eventid)
            {
                Event e = EventControl.RetrieveEvent(eventid);
                Member s = MemberControls.RetrieveMember(sender.ToString());

                string msg = String.Format(acceptedEventMsg, s.Name, e.EventTitle);

                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }

            public static void SendAcceptedToGroup(int sender, int receiver, string groupid)
            {
                Group g = GroupControl.RetrieveGroup(groupid);
                Member s = MemberControls.RetrieveMember(sender.ToString());

                string msg = String.Format(acceptedGroupMsg, s.Name, g.GroupName);

                NotificationControl.CreateNotification(sender, receiver, msg, DateTime.Now);
            }


            public static string GetServerUrl(HttpRequest request)
            {
                return request.Url.GetLeftPart(UriPartial.Authority).ToString();
            }


        #endregion
    }
}   